package com.scoutmobmap.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.Id;

import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.Objectify;

public class OfferList {
  public static OfferList getOfferList(Objectify ofy) {
    try {
      return ofy.get(OfferList.class, "singleton");
    } catch (NotFoundException e) {
      OfferList firstOne = new OfferList();
      firstOne.lastUpdated = new Date(0L);
      ofy.put(firstOne);
      return firstOne;
    }
  }
  
  public static void deleteOfferList(Objectify ofy) {
    ofy.delete(getOfferList(ofy));
  }
  
  public static boolean updateOfferList(Objectify ofy) {
    OfferList offerList = OfferList.getOfferList(ofy);
    boolean isNew = offerList.updateOfferList();
    if (isNew) { ofy.put(offerList); }
    return isNew;
  }
  
  @Id String id = "singleton";
  public Set<String> offerIds;
  public Date lastUpdated;
  
  public boolean updateOfferList() {
    Date now = new Date();
    long diff = now.getTime() - lastUpdated.getTime();
    long MS_IN_DAY = 24 * 60 * 60 * 1000;
    if (diff > MS_IN_DAY) {
      Set<String> temp = getAllSFDeals();
      if (temp != null) {
        offerIds = temp;
        lastUpdated = now;
        return true;
      }
    }
    return false;
  }
  
  private Set<String> getAllSFDeals() {
    Set<String> allDeals = new HashSet<String>();
    try {
      URL url = new URL("http://www.scoutmob.com/san-francisco/past_deals");
      BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
      String line;
      while ((line = reader.readLine()) != null) {
        if (line.contains("san-francisco/deal/")) {
          int idx = line.indexOf("san-francisco/deal/");
          String dealId = line.substring(idx + "san-francisco/deal/".length());
          idx = dealId.indexOf('"');
          dealId = dealId.substring(0, idx);
          allDeals.add(dealId);
        }
      }
      reader.close();
    } catch (MalformedURLException e) {
      return null;
    } catch (IOException e) {
      return null;
    }
    return allDeals;
  }
}
